package concurrency.chapter6;

public class ThreadService {
    private Thread executeThread;
    private boolean finished = false;

    //定义一个执行线程，执行线程退出时守护线程也就退出了
    public void execute(Runnable task) {

        executeThread = new Thread() {
            @Override
            public void run() {
                //创建一个守护线程
                Thread runner = new Thread(task);
                runner.setDaemon(true);
                runner.start();
                try {
                    //当前线程executeThread去join的，用executeThread去打断
                    runner.join();
                    finished = true;
                } catch (InterruptedException e) {
                    //e.printStackTrace();
                }
            }
        };
        executeThread.start();
    }

    public void shutdown(long mills) {
        long currentTime = System.currentTimeMillis();
        while (!finished) {
            if ((System.currentTimeMillis() - currentTime) > mills) {
                System.out.println("任务超时，需要结束它");
                executeThread.interrupt();
                break;
            }

            try {
                //通过短暂的休眠，若被打断则抛异常InterruptedException
                executeThread.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("执行线程被打断");
                break;
            }
        }
        finished = false;//把状态还原为初始
    }
}
